<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>编辑优惠卷表</title>
	<#include "/common/vue_resource.ftl">
</head>
<body>
<div id="app" v-cloak>
	<div class="ui-form">
        <el-form ref="record" :rules="rules" :model="record" label-width="80px">
            <el-form-item label="类型" prop="type">
                <el-select v-model="record.type" placeholder="请选择优惠券类型">
                    <el-option v-for="type in typeList" :label="type.name" :value="type.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="名称" prop="name">
                <el-input v-model="record.name"></el-input>
            </el-form-item>
            <el-form-item label="平台" prop="platform">
                <el-select v-model="record.platform" placeholder="请选择适用平台">
                    <el-option v-for="platform in platformList" :label="platform.name" :value="platform.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="数量" prop="count">
                <el-input v-model="record.count"></el-input>
            </el-form-item>
            <el-form-item label="面额" prop="amount">
                <el-input placeholder="请输入面额" v-model="record.amount">
                    <template slot="append">元</template>
                </el-input>
            </el-form-item>
            <el-form-item label="每人限领" prop="perLimit">
                <el-input v-model="record.perLimit">
                    <template slot="append">张</template>
                </el-input>
            </el-form-item>
            <el-form-item label="使用门槛" prop="minPoint">
                <el-input v-model="record.minPoint">
                    <template slot="prepend">满</template>
                    <template slot="append">元可用</template>
                </el-input>
            </el-form-item>
            <el-form-item label="开始日期" prop="startTime">
                <el-col :span="11">
                    <el-date-picker type="date" placeholder="开始日期" v-model="record.startTime" style="width: 100%;"></el-date-picker>
                </el-col>
            </el-form-item>
            <el-form-item label="结束日期" prop="endTime">
                <el-col :span="11">
                    <el-date-picker type="date" placeholder="结束日期" v-model="record.endTime" style="width: 100%;"></el-date-picker>
                </el-col>
            </el-form-item>
            <el-form-item label="可用商品" prop="useType">
                <el-radio-group v-model="record.useType" @change="change">
                    <el-radio-button label="0">全场通用</el-radio-button>
                    <el-radio-button label="1">指定分类</el-radio-button>
                    <el-radio-button label="2">指定商品</el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item v-if="record.useType == 1">
                <el-cascader clearable
                             v-model="categoryIds"
                             :options="categoryList"
                             @change="changeCategory"></el-cascader>
                <el-button @click="addCategory">添加</el-button>
            </el-form-item>
            <el-form-item v-if="record.useType == 1">
                <el-table
                        :data="selectedCategoryList"
                        border
                        style="width: 560px; text-align: center;">
                    <el-table-column
                            label="分类名称"
                            width="280">
                        <template slot-scope="scope">
                            {{scope.row.parentCategoryName}}>{{scope.row.productCategoryName}}
                        </template>
                    </el-table-column>
                    <el-table-column
                            label="操作"
                            width="279">
                        <template slot-scope="scope">
                            <el-button type="text" @click="removeSelectCategory(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>

            <el-form-item v-if="record.useType == 2">
                <el-autocomplete
                        v-model="productName"
                        placeholder="商品名称/货号"
                        @select="handleSelect"
                        :fetch-suggestions="querySearchAsync"
                ></el-autocomplete>
                <el-button @click="addProduct">添加</el-button>
            </el-form-item>

            <el-form-item v-if="record.useType == 2">
                <el-table
                        :data="productList"
                        border
                        style="width: 600px; text-align: center;">
                    <el-table-column
                            label="商品名称"
                            width="250"
                            prop="name">
                    </el-table-column>
                    <el-table-column
                            label="货号"
                            width="250"
                            prop="productSn">
                    </el-table-column>
                    <el-table-column
                            label="操作"
                            width="99">
                        <template slot-scope="scope">
                            <el-button type="text" @click="removeSelectproduct(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>

            <el-form-item label="备注">
                <el-input type="textarea" v-model="record.note"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="addCoupon('record')">保存</el-button>
                <el-button @click="cancel">取消</el-button>
            </el-form-item>
        </el-form>
	</div>
</div>
<script>
	var app = new Vue({
		el: '#app',
		data: {
			showTypes: false,
			record : {
				id:'${params.id!}',
				id:'',
				type:'',
				name:'',
				platform:'',
				count:'',
				amount:'',
				perLimit:'',
				minPoint:'',
				startTime:'',
				endTime:'',
				useType:'',
				note:'',
				publishCount:'',
				useCount:'',
				receiveCount:'',
				enableTime:'',
				code:'',
				memberLevel:'',
				isDel:'',
				createId:'',
				createTime:'',
				modifyId:'',
				modifyTime:'',
                categoryRelationList: [],
                productRelationList: [],
                couponHistoryList: []
			},
			typeList: [],
            platformList: [],
            categoryList: [],
            selectedCategoryList: [],
            categoryName: '',
            productCategoryId: '',
            categoryIds: [],
            productName: '',
            productList: [],
            product: {},
            rules: {
                type: [
                    { required: true, message: '请选择类型', trigger: 'change' }
                ],
                name: [
                    { required: true, message: '请输入优惠券名称', trigger: 'blur' }
                ],
                platform: [
                    { required: true, message: '请选择平台', trigger: 'change' }
                ],
                startTime: [
                    {type: 'date', required: true, message: '请选择开始时间', trigger: 'change' }
                ],
                endTime: [
                    { type: 'date', required: true, message: '请选择结束时间', trigger: 'change' }
                ],
                status: [
                    { required: true, message: '请选择状态', trigger: 'change' }
                ],
                useType: [
                    { required: true, message: '请选择使用类型', trigger: 'change' }
                ],
                count: [
                    { required: true, message: '请输入数量', trigger: 'blur' }
                ],
                amount: [
                    { required: true, message: '请输入金额', trigger: 'blur' }
                ],
                perLimit: [
                    { required: true, message: '请输入没人限领数量', trigger: 'blur' }
                ],
                minPoint: [
                    { required: true, message: '请输入使用门槛', trigger: 'blur' }
                ]
            }
		},
		mounted: function () {
			this.init();
			this.loadData();
			this.loadCategory();
		},
		methods: {
			init:function(){
				var that = this;
				/*laydate.render({elem: '#beginDate', type:'datetime', done:function (value) {
						that.record.beginDate = value;
					}});*/

			},
			loadData: function () {
				var that = this;
				$.http.post('${params.contextPath}/web/smsCoupon/query.json', {id: '${params.id!}'}).then(function (data) {
                    that.typeList = data.data.typeList;
                    that.platformList = data.data.platformList;
                    that.record = data.data.record;
                    that.selectedCategoryList = data.data.record.categoryRelationList;
                    that.productList = data.data.record.productRelationList;
				});
			},
            change: function(val) {
                var that = this;
                if (val == '0') {
                    that.productList = [];
                    that.selectedCategoryList = [];
                    that.productName = '';
                    that.categoryIds = [];
                } else if (val == '1') {
                    that.productList = [];
                    that.productName = '';
                } else if (val == '2') {
                    that.selectedCategoryList = [];
                    that.categoryIds = [];
                }
            },
            loadCategory: function () {
			    var that = this;
                // 查询商品分类列表
                $.http.post('${params.contextPath}/web/pmsProductCategory/queryList.json').then(function (data) {
                    console.log(data);
                    var list = data.data, map = {}, categoryMap = {};
                    for (var i = 0; i < list.length; i ++) {
                        var item = list[i];
                        map[item.id] = item;
                        item.value = item.id;
                        item.label = item.name;
                        categoryMap[item.id] = item;
                    }
                    that.categoryMap = categoryMap;

                    for (var i = 0; i < list.length; i ++) {
                        var item = list[i];
                        var parent = map[item.parentId];
                        if (!parent) {
                            continue;
                        }
                        var children = parent.children || [];
                        children.push(item);
                        parent.children = children;
                        map[item.id] = null;
                    }

                    var resultList = [];
                    for (var key in map) {
                        var item = map[key];
                        if (!item) {
                            continue;
                        }
                        resultList.push(item);
                    }
                    console.log(resultList);
                    that.categoryList = resultList;
                })
            },
            changeCategory: function(value) {
                console.log(value);
                this.productCategoryId = value[1];
            },
            addCategory: function() {
			    if (this.categoryIds == null || this.categoryIds.length == 0) {
                    this.$message.error('请选择商品分类!');
                    return false;
                }
                this.categoryName = this.getCascaderObj(this.categoryIds, this.categoryList);
			    var cate = {};
                cate.productCategoryName = this.categoryName[1].name;
                cate.parentCategoryName = this.categoryName[0].name;
                cate.productCategoryId = this.productCategoryId;
                this.selectedCategoryList.push(cate);
            },
            getCascaderObj: function(val,opt) {
                return val.map(function (value, index, array) {
                    for (var itm of opt) {
                        if (itm.value == value) { opt = itm.children; return itm; }
                    }
                    return null;
                });
            },
            removeSelectCategory: function(row) {
			    var newList = [];
                var selectId = row.productCategoryId;
                for (var i = 0; i < this.selectedCategoryList.length; i++) {
                    if (selectId != this.selectedCategoryList[i].productCategoryId) {
                        newList.push(this.selectedCategoryList[i]);
                    }
                }
                this.selectedCategoryList = newList;
            },
            handleSelect: function(item) {
			    console.log(item);
			    this.product = item;
            },
            querySearchAsync: function(queryString, cb) {
			    if (queryString != null && queryString != '') {
                    $.http.post("${params.contextPath}/web/pmsProduct/listAll.json", queryString).then(function (data) {
                        var result = data.data;
                        console.log(result);
                        if (result != null && result.length > 0) {
                            for (var item in result) {
                                result[item].value = result[item].name;
                            }
                        }
                        cb(result);
                    });
                }
            },
            addProduct: function() {
                if (this.product == null) {
                    this.$message.error('请选择商品!');
                    return false;
                }
                this.productList.push(this.product);
            },
            removeSelectproduct: function(row) {
                var newList = [];
                var selectId = row.id;
                for (var i = 0; i < this.productList.length; i++) {
                    if (selectId != this.productList[i].id) {
                        newList.push(this.productList[i]);
                    }
                }
                this.productList = newList;
            },
            addCoupon: function (formName) {
                var that = this;
                that.record.categoryRelationList = that.selectedCategoryList;
                that.record.productRelationList = that.productList;
                console.log(that.record);
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        $.http.post('${params.contextPath}/web/smsCoupon/<#if (params.id)??>modify<#else>save</#if>.json', {'couponStr': JSON.stringify(this.record)}).then(function (data) {
                            if (!data.success) {
                                $.message(data.message);
                                return;
                            }
                            var alt = layer.alert(data.message || "操作成功", function () {
                                parent.app.loadData();
                                parent.layer.closeAll();
                                layer.close(alt);
                            });
                        });
                    } else {
                        return false;
                    }
                });
            },
            cancel: function () {
                parent.app.loadData();
                parent.layer.closeAll();
            }
		}
	});
</script>
</body>

</html>
